package com.study.mike.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.study.mike.common.constants.RedisKey;
import com.study.mike.common.enums.BizCodeEnum;
import com.study.mike.common.enums.OrderStatusEnum;
import com.study.mike.common.exception.BizException;
import com.study.mike.common.utils.StrUtils;
import com.study.mike.mapper.OrderMapper;
import com.study.mike.model.dto.PageDTO;
import com.study.mike.model.dto.QuerySaleOrderProductDTO;
import com.study.mike.model.dto.SaleOrderDTO;
import com.study.mike.model.entity.SaleOrder;
import com.study.mike.model.entity.SaleOrderProduct;
import com.study.mike.model.po.*;
import com.study.mike.service.OrderService;
import com.study.mike.service.SaleOrderProductService;
import com.study.mike.service.SaleProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author KangHui
 * @Date 2022/8/29 17:15
 */
@Slf4j
@Service
@CacheConfig(cacheNames = RedisKey.ONE_HOUR)
public class OrderServiceImpl extends ServiceImpl<OrderMapper, SaleOrder> implements OrderService {
    @Resource
    private OrderMapper orderMapper;

    @Resource
    private SaleProductService saleProductService;

    @Resource
    private SaleOrderProductService saleOrderProductService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(allEntries = true)
    public SaleOrderDTO createOrder(AddOrderPO addOrderPO) {
        SaleOrder saleOrder = new SaleOrder();
        BeanUtils.copyProperties(addOrderPO, saleOrder);
        try {
            this.save(saleOrder);
            // 订单商品
            List<SaleOrderProduct> saleOrderProducts = new ArrayList<>();
            addOrderPO.getSaleOrderProducts().forEach(item -> {
                SaleOrderProduct saleOrderProduct = new SaleOrderProduct();
                // 订单号
                saleOrderProduct.setOrderId(saleOrder.getId());
                // 商品id
                saleOrderProduct.setProductId(item.getProductId());
                // 商品数量
                saleOrderProduct.setProductNum(item.getProductNum());
                // 计算此类商品总价
                BigDecimal priceTotal = item.getProductPrice().multiply(new BigDecimal(item.getProductNum()));
                saleOrderProduct.setTotalPrice(priceTotal);
                saleOrderProducts.add(saleOrderProduct);
            });
            saleOrderProductService.saveBatch(saleOrderProducts);
        } catch (DuplicateKeyException e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new BizException("400", "订单创建失败");
        }
        SaleOrderDTO saleOrderDTO = new SaleOrderDTO();
        BeanUtils.copyProperties(saleOrder, saleOrderDTO);
        return saleOrderDTO;
    }

    @Override
    @Cacheable(key = "#root.method.name + #po.pageCurrent + #po.pageSize")
    public PageDTO<SaleOrderDTO> querySaleOrder(QuerySaleOrderPO po) {
        LambdaQueryWrapper<SaleOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StrUtil.isNotBlank(po.getOrderSn()), SaleOrder::getOrderSn, po.getOrderSn())
                .eq(ObjectUtil.isNotEmpty(po.getStatus()), SaleOrder::getStatus, po.getStatus());
        PageDTO<SaleOrder> page = new PageDTO<>(po.getPageCurrent(), po.getPageSize());
        IPage<SaleOrder> pages = orderMapper.selectPage(page, wrapper);
        List<SaleOrderDTO> saleOrderDTOList = pages.getRecords().stream().map(x -> {
            SaleOrderDTO saleOrderDTO = new SaleOrderDTO();
            BeanUtils.copyProperties(x, saleOrderDTO);
            return saleOrderDTO;
        }).collect(Collectors.toList());
        PageDTO<SaleOrderDTO> result = new PageDTO<>(pages.getCurrent(), pages.getSize(), pages.getTotal());
        result.setRecords(saleOrderDTOList);
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(allEntries = true)
    public Boolean editOrder(EditOrderPO po) {
        SaleOrder saleOrder = new SaleOrder();
        BeanUtils.copyProperties(po, saleOrder);
        return this.updateById(saleOrder);
    }

    @Override
    public Boolean deleteOrder(DeleteOrderPO po) {
        LambdaQueryWrapper<SaleOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SaleOrder::getOrderSn, po.getOrderId())
                .or().eq(SaleOrder::getId, Integer.valueOf(po.getOrderId()));
        return orderMapper.delete(wrapper) > 0;
    }

    @Override
    public Boolean confirmOrder(ConfirmOrderPO po) {
        SaleOrder saleOrder = this.operation(po);
        // 只有已审核订单才能正常确认
        if (!ObjectUtil.equal(OrderStatusEnum.EXAMINE, saleOrder.getStatus())) {
            throw new BizException(BizCodeEnum.FIND_NO_ONE.getCode(), "当前订单状态无法确认");
        }
        saleOrder.setStatus(OrderStatusEnum.VERIFY);
        return orderMapper.updateById(saleOrder) > 0;
    }

    @Override
    public QuerySaleOrderProductDTO queryOrderInfo(SaleOrderProductInfoPO productInfoPO) {
        // 如果传的是订单号 通过订单号获取到数据id
        String orderSn = productInfoPO.getOrderSn();
        if (ObjectUtil.isEmpty(productInfoPO.getOrderId()) && ObjectUtil.isNotEmpty(orderSn)) {
            LambdaQueryWrapper<SaleOrder> lw = new LambdaQueryWrapper<>();
            lw.select(SaleOrder::getId).eq(SaleOrder::getOrderSn, orderSn);
            SaleOrder saleOrder = orderMapper.selectOne(lw);
            productInfoPO.setOrderId(saleOrder.getId());
        }
        return orderMapper.queryOrderInfo(productInfoPO.getOrderId());
    }

    @Override
    public Boolean examine(ConfirmOrderPO po) {
        SaleOrder saleOrder = this.operation(po);
        // 只有已发起订单才能正常审核
        if (!ObjectUtil.equal(OrderStatusEnum.INITIATE, saleOrder.getStatus())) {
            throw new BizException(BizCodeEnum.FIND_NO_ONE.getCode(), "当前订单状态无法审核");
        }
        saleOrder.setStatus(OrderStatusEnum.EXAMINE);
        return orderMapper.updateById(saleOrder) > 0;
    }

    @Override
    public Boolean complete(ConfirmOrderPO po) {
        SaleOrder saleOrder = this.operation(po);
        // 只有已确认的订单才能操作完成
        if (!ObjectUtil.equal(OrderStatusEnum.VERIFY, saleOrder.getStatus())) {
            throw new BizException(BizCodeEnum.FIND_NO_ONE.getCode(), "当前订单状态无法操作完成");
        }
        saleOrder.setStatus(OrderStatusEnum.COMPLETE);
        return orderMapper.updateById(saleOrder) > 0;
    }

    private SaleOrder operation(ConfirmOrderPO po) {
        // 订单存在验证
        LambdaQueryWrapper<SaleOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SaleOrder::getOrderSn, po.getOrderId());
        // todo 若订单号存在字母的情况无法直接做以上处理
        if (StrUtils.verifyOrder(po.getOrderId())) {
            wrapper.or().eq(SaleOrder::getId, Long.valueOf(po.getOrderId()));
        }
        if (this.count(wrapper) == 0) {
            throw new BizException(BizCodeEnum.FIND_NO_ONE.getCode(), BizCodeEnum.FIND_NO_ONE.getMsg());
        }
        SaleOrder saleOrder = this.getOne(wrapper);
        return saleOrder;
    }
}
